import React, { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Mail, Phone, Eye, EyeOff, Loader2, CheckCircle, AlertCircle, User } from 'lucide-react'
import { useAuth } from '../contexts/AuthContext'
import '../styles/auth.css'

type RegisterMethod = 'email' | 'phone'

const RegisterPage: React.FC = () => {
  const navigate = useNavigate()
  const { registerWithEmail, loginWithPhone, sendPhoneCode, isLoggedIn } = useAuth()

  const [registerMethod, setRegisterMethod] = useState<RegisterMethod>('email')
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  // 邮箱注册状态
  const [emailData, setEmailData] = useState({
    email: '',
    password: '',
    confirmPassword: '',
    username: '',
    showPassword: false,
    showConfirmPassword: false
  })

  // 手机注册状态
  const [phoneData, setPhoneData] = useState({
    phone: '',
    code: '',
    username: '',
    codeSent: false,
    countdown: 0,
    devCode: '' // 开发环境显示的验证码
  })

  // 如果已登录，重定向到首页
  useEffect(() => {
    if (isLoggedIn) {
      navigate('/', { replace: true })
    }
  }, [isLoggedIn, navigate])

  // 验证码倒计时
  useEffect(() => {
    let timer: number
    if (phoneData.countdown > 0) {
      timer = setTimeout(() => {
        setPhoneData(prev => ({ ...prev, countdown: prev.countdown - 1 }))
      }, 1000) as unknown as number
    }
    return () => clearTimeout(timer)
  }, [phoneData.countdown])

  // 邮箱注册
  const handleEmailRegister = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 验证必填字段
    if (!emailData.email || !emailData.password || !emailData.confirmPassword) {
      setMessage({ type: 'error', text: '请填写所有必填字段' })
      return
    }

    // 验证密码一致性
    if (emailData.password !== emailData.confirmPassword) {
      setMessage({ type: 'error', text: '两次输入的密码不一致' })
      return
    }

    // 验证密码强度
    if (emailData.password.length < 6) {
      setMessage({ type: 'error', text: '密码长度至少6位' })
      return
    }

    setLoading(true)
    setMessage(null)

    try {
      const result = await registerWithEmail(
        emailData.email, 
        emailData.password, 
        emailData.username || undefined
      )
      
      if (result.success) {
        setMessage({ type: 'success', text: result.message })
        // 注册成功后，useEffect会自动重定向
      } else {
        setMessage({ type: 'error', text: result.message })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '注册失败，请重试' })
    } finally {
      setLoading(false)
    }
  }

  // 发送验证码
  const handleSendCode = async () => {
    if (!phoneData.phone) {
      setMessage({ type: 'error', text: '请输入手机号' })
      return
    }

    if (!/^1[3-9]\d{9}$/.test(phoneData.phone)) {
      setMessage({ type: 'error', text: '手机号格式不正确' })
      return
    }

    setLoading(true)
    setMessage(null)

    try {
      const result = await sendPhoneCode(phoneData.phone, 'register')
      
      if (result.success) {
        setMessage({ type: 'success', text: result.message })
        setPhoneData(prev => ({
          ...prev,
          codeSent: true,
          countdown: 60,
          devCode: result.dev_code || '' // 开发环境显示验证码
        }))
      } else {
        setMessage({ type: 'error', text: result.message })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '发送验证码失败，请重试' })
    } finally {
      setLoading(false)
    }
  }

  // 手机注册
  const handlePhoneRegister = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!phoneData.phone || !phoneData.code) {
      setMessage({ type: 'error', text: '请输入手机号和验证码' })
      return
    }

    setLoading(true)
    setMessage(null)

    try {
      const result = await loginWithPhone(
        phoneData.phone, 
        phoneData.code, 
        phoneData.username || undefined
      )
      
      if (result.success) {
        setMessage({ type: 'success', text: result.message })
        // 注册成功后，useEffect会自动重定向
      } else {
        setMessage({ type: 'error', text: result.message })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '注册失败，请重试' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-50 via-pink-50 to-indigo-50 flex items-center justify-center p-4 relative overflow-hidden">
      {/* 背景装饰 */}
      <div className="absolute inset-0">
        <div className="absolute top-20 left-16 w-36 h-36 bg-purple-200 rounded-full opacity-20 animate-pulse delay-300"></div>
        <div className="absolute top-32 right-12 w-28 h-28 bg-pink-200 rounded-full opacity-20 animate-pulse delay-700"></div>
        <div className="absolute bottom-32 left-8 w-44 h-44 bg-indigo-200 rounded-full opacity-20 animate-pulse delay-1500"></div>
        <div className="absolute bottom-16 right-16 w-32 h-32 bg-blue-200 rounded-full opacity-20 animate-pulse delay-100"></div>
      </div>

      <div className="max-w-md w-full space-y-4 relative z-10">
        {/* 头部 */}
        <div className="text-center">
          <div className="mx-auto w-16 h-16 bg-gradient-to-r from-purple-600 to-pink-600 rounded-2xl flex items-center justify-center mb-4 shadow-xl auth-float auth-pulse-glow">
            <span className="text-xl font-bold text-white">AI</span>
          </div>
          <h2 className="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent">
            加入 AIDE
          </h2>
          <p className="mt-3 text-theme-text-secondary">
            开启您的智能效率之旅
          </p>
          <p className="mt-2 text-sm text-theme-text-secondary">
            已有账号？{' '}
            <Link to="/login" className="text-purple-600 hover:text-purple-700 font-semibold transition-colors">
              立即登录 →
            </Link>
          </p>
        </div>

        {/* 主卡片 */}
        <div className="bg-theme-bg/80 backdrop-blur-xl rounded-3xl shadow-2xl border border-white/20 p-6 space-y-4 auth-card transition-all duration-300">
          {/* 注册方式切换 */}
          <div className="flex rounded-2xl bg-theme-bg-secondary/80 p-1.5 backdrop-blur-sm">
            <button
              onClick={() => setRegisterMethod('email')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl text-sm font-semibold transition-all duration-300 ${
                registerMethod === 'email'
                  ? 'bg-theme-bg text-purple-600 shadow-lg shadow-purple-100 transform scale-105'
                  : 'text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg/50'
              }`}
            >
              <Mail className="w-4 h-4" />
              邮箱注册
            </button>
            <button
              onClick={() => setRegisterMethod('phone')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl text-sm font-semibold transition-all duration-300 ${
                registerMethod === 'phone'
                  ? 'bg-theme-bg text-purple-600 shadow-lg shadow-purple-100 transform scale-105'
                  : 'text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg/50'
              }`}
            >
              <Phone className="w-4 h-4" />
              手机注册
            </button>
          </div>

          {/* 消息提示 */}
          {message && (
            <div className={`flex items-center gap-3 p-4 rounded-2xl text-sm font-medium ${
              message.type === 'success' 
                ? 'bg-green-50 text-green-800 border border-green-200/50 shadow-sm' 
                : 'bg-red-50 text-red-800 border border-red-200/50 shadow-sm'
            }`}>
              {message.type === 'success' ? (
                <CheckCircle className="w-5 h-5" />
              ) : (
                <AlertCircle className="w-5 h-5" />
              )}
              {message.text}
            </div>
          )}

          {/* 开发环境验证码显示 */}
          {phoneData.devCode && (
            <div className="bg-gradient-to-r from-yellow-50 to-amber-50 border border-yellow-200/50 rounded-2xl p-4 shadow-sm">
              <p className="text-sm text-yellow-800 font-medium">
                <strong>🔑 开发环境验证码：</strong> 
                <span className="font-mono text-lg ml-2 px-2 py-1 bg-yellow-100 rounded-lg">{phoneData.devCode}</span>
              </p>
            </div>
          )}

          {/* 邮箱注册表单 */}
          {registerMethod === 'email' && (
            <form onSubmit={handleEmailRegister} className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="email" className="block text-sm font-semibold text-theme-text">
                  邮箱地址 *
                </label>
                <div className="relative">
                  <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 pointer-events-none" />
                  <input
                    id="email"
                    type="email"
                    required
                    value={emailData.email}
                    onChange={(e) => setEmailData(prev => ({ ...prev, email: e.target.value }))}
                    className="w-full pl-12 pr-4 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="输入您的邮箱地址"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="username" className="block text-sm font-semibold text-theme-text">
                  用户名 (可选)
                </label>
                <div className="relative">
                  <User className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 pointer-events-none" />
                  <input
                    id="username"
                    type="text"
                    value={emailData.username}
                    onChange={(e) => setEmailData(prev => ({ ...prev, username: e.target.value }))}
                    className="w-full pl-12 pr-4 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="输入您的用户名"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="password" className="block text-sm font-semibold text-theme-text">
                  密码 *
                </label>
                <div className="relative">
                  <input
                    id="password"
                    type={emailData.showPassword ? 'text' : 'password'}
                    required
                    value={emailData.password}
                    onChange={(e) => setEmailData(prev => ({ ...prev, password: e.target.value }))}
                    className="w-full pl-4 pr-12 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg"
                    placeholder="至少6位密码"
                  />
                  <button
                    type="button"
                    onClick={() => setEmailData(prev => ({ ...prev, showPassword: !prev.showPassword }))}
                    className="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-theme-text-secondary transition-colors"
                  >
                    {emailData.showPassword ? (
                      <EyeOff className="w-5 h-5" />
                    ) : (
                      <Eye className="w-5 h-5" />
                    )}
                  </button>
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="confirmPassword" className="block text-sm font-semibold text-theme-text">
                  确认密码 *
                </label>
                <div className="relative">
                  <input
                    id="confirmPassword"
                    type={emailData.showConfirmPassword ? 'text' : 'password'}
                    required
                    value={emailData.confirmPassword}
                    onChange={(e) => setEmailData(prev => ({ ...prev, confirmPassword: e.target.value }))}
                    className="w-full pl-4 pr-12 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg"
                    placeholder="再次输入密码"
                  />
                  <button
                    type="button"
                    onClick={() => setEmailData(prev => ({ ...prev, showConfirmPassword: !prev.showConfirmPassword }))}
                    className="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-theme-text-secondary transition-colors"
                  >
                    {emailData.showConfirmPassword ? (
                      <EyeOff className="w-5 h-5" />
                    ) : (
                      <Eye className="w-5 h-5" />
                    )}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full flex justify-center items-center gap-2 py-4 px-6 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white font-semibold rounded-2xl shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-[1.02] active:scale-[0.98]"
              >
                {loading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <>
                    <Mail className="w-5 h-5" />
                    注册账号
                  </>
                )}
              </button>
            </form>
          )}

          {/* 手机注册表单 */}
          {registerMethod === 'phone' && (
            <form onSubmit={handlePhoneRegister} className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="phone" className="block text-sm font-semibold text-theme-text">
                  手机号码 *
                </label>
                <div className="relative">
                  <Phone className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 pointer-events-none" />
                  <input
                    id="phone"
                    type="tel"
                    required
                    value={phoneData.phone}
                    onChange={(e) => setPhoneData(prev => ({ ...prev, phone: e.target.value.replace(/\D/g, '') }))}
                    className="w-full pl-12 pr-4 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="输入您的手机号码"
                    maxLength={11}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="phoneUsername" className="block text-sm font-semibold text-theme-text">
                  用户名 (可选)
                </label>
                <div className="relative">
                  <User className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 pointer-events-none" />
                  <input
                    id="phoneUsername"
                    type="text"
                    value={phoneData.username}
                    onChange={(e) => setPhoneData(prev => ({ ...prev, username: e.target.value }))}
                    className="w-full pl-12 pr-4 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="输入您的用户名"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="phoneCode" className="block text-sm font-semibold text-theme-text">
                  验证码 *
                </label>
                <div className="flex gap-2">
                  <input
                    id="phoneCode"
                    type="text"
                    required
                    value={phoneData.code}
                    onChange={(e) => setPhoneData(prev => ({ ...prev, code: e.target.value.replace(/\D/g, '') }))}
                    className="flex-1 px-4 py-3 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="6位验证码"
                    maxLength={6}
                  />
                  <button
                    type="button"
                    onClick={handleSendCode}
                    disabled={loading || phoneData.countdown > 0}
                    className="px-4 py-3 border border-theme-border rounded-2xl text-xs font-semibold text-theme-text-secondary bg-theme-bg hover:bg-theme-bg-secondary focus:outline-none focus:ring-2 focus:ring-purple-500/20 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 hover:shadow-md whitespace-nowrap"
                  >
                    {phoneData.countdown > 0 ? `${phoneData.countdown}s` : '发送'}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading || !phoneData.codeSent}
                className="w-full flex justify-center items-center gap-2 py-4 px-6 bg-gradient-to-r from-pink-600 to-pink-700 hover:from-pink-700 hover:to-pink-800 text-white font-semibold rounded-2xl shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-[1.02] active:scale-[0.98]"
              >
                {loading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <>
                    <Phone className="w-5 h-5" />
                    注册账号
                  </>
                )}
              </button>
            </form>
          )}
        </div>

        {/* 底部提示 */}
        <div className="text-center space-y-2">
          <p className="text-xs text-theme-text-muted">
            注册即表示您同意我们的
            <button className="text-purple-600 hover:text-purple-700 mx-1 underline">服务条款</button>
            和
            <button className="text-purple-600 hover:text-purple-700 mx-1 underline">隐私政策</button>
          </p>
          <div className="flex items-center justify-center space-x-3 text-xs text-gray-400">
            <span>© 2024 AIDE</span>
            <span>•</span>
            <span>智能助手</span>
          </div>
        </div>
      </div>
    </div>
  )
}

export default RegisterPage
